/**
 * 递归法，数组拼接树，需要预知根id
 * @param {Number} id 根id
 * @param {Array} list 列表
 * @returns 树
 */

/**
 * 列表转换成树
 * @param {Array} list 列表
 * @returns 树
 */
function listToTree(list) {
  const tree = [];

  const nodeMap = new Map();
  for (const node of list) {
    nodeMap.set(node.id, { children: [], ...node });
  }

  for (const node of nodeMap.values()) {
    const parent = nodeMap.get(node.pid);
    (parent ? parent.children : tree).push(node);
  }

  return tree;
}

/**
 * 树转换成列表
 * @param {Array} tree 树
 * @returns 列表
 */
function treeToList(tree) {
  const list = [...tree];
  for (let i = 0; i < list.length; i++) {
    const { children } = list[i];
    if (children) list.splice(i + 1, 0, ...children);
  }
  return list;
}

export { listToTree, treeToList };
